<script lang="ts" setup>
/**
 * Props
 * @config 配置项 --[{ label: string, key: BaseType, disabled?: boolean }, ...]
 * 必传
 *
 * @value 默认选中key值
 *
 * @multiple 是否多选
 * 默认 false
 *
 * @position 组件内容排序
 * 默认 center 可选 left | center | right
 *
 * @width 组件宽度
 *
 * @height 组件高度
 *
 * Emits
 * @value 返回当前选中值
 *
 * Expose
 * @change 手动改变当前选中key值
 */
import { computed, ref, watch } from 'vue'
import { hasUnit } from '@U/common'
import type { BaseType, IObj, PropType } from '@/interface'

const props = defineProps({
  config: {
    type: Object as PropType<Array<IObj>>,
    required: true,
  },
  position: {
    type: String as PropType<'left' | 'center' | 'right'>,
    required: false,
    default: 'center',
  },
  value: {
    type: String as PropType<BaseType | Array<BaseType>>,
    required: false,
    default: '',
  },
  width: {
    type: String,
    required: false,
    default: '',
  },
  height: {
    type: String,
    required: false,
    default: '',
  },
  multiple: {
    type: Boolean,
    required: false,
    default: false,
  },
})
const emits = defineEmits(['update:value', 'value'])
defineExpose({
  change,
})

// config
const _config = props.config?.map((i: IObj) => ({ text: i.label, value: i.key, disable: i.disabled }))
// position
const _position = () => {
  switch (props?.position) {
    case 'center': return 'center'
    case 'left': return 'flex-start'
    case 'right': return 'flex-end'
  }
}

// 当前选中值
const act = ref(<BaseType | Array<BaseType>>props.value)
function change(key: BaseType | Array<BaseType>) {
  act.value = key
}
const changeCheckbox = (e:IObj) => {
  act.value = e.detail.value
}
watch(
    () => act.value,
    (newVal: BaseType | Array<BaseType>) => {
      emits('value', newVal)
      emits('update:value', newVal)
    },
)
const pro_v = computed(() => props.value)
watch(
    () => pro_v.value,
    (newVal: BaseType | Array<BaseType>) => { act.value = newVal },
)

</script>

<template>
  <div :style="{justifyContent: _position(), width: width ? hasUnit(width) : '100%', height: height ? hasUnit(height) : '100%'}" class="prm-radio">
    <uni-data-checkbox v-model="act" :localdata="_config" :multiple="multiple" selected-color="#1890FF" @change="changeCheckbox" />
  </div>
</template>

<style lang="less" scoped>
.prm-radio {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  margin-left: 16rpx;
  overflow: hidden;
}
</style>
